package utils;

import book.Book;
import book.PairOfUidAndBookId;
import com.bit.utils.FileUtils;

import java.io.IOException;
import java.time.LocalDate;

public class AnalyzingBorrowedBook {
    public void storeObject(PairOfUidAndBookId[] pairOfUidAndBookIds,String filename)throws IOException{
        int booksUserLen = 0;
        for (int i = 0; i < pairOfUidAndBookIds.length; i++) {
            if(pairOfUidAndBookIds[i] != null){
                booksUserLen++;
            }
        }
        StringBuilder jsonArrays = new StringBuilder();
        for (int i = 0; i < booksUserLen; i++) {
            if(pairOfUidAndBookIds[i] != null){
                jsonArrays.append(pairOfUidAndBookIds[i].toJson());
                if(i != booksUserLen - 1){
                    jsonArrays.append("\n");
                }
            }
        }
        FileUtils.writeFile(jsonArrays.toString(),filename);
    }
    public PairOfUidAndBookId[] loadObject(String filename) throws IOException{
        String content = FileUtils.readFile(filename);
        if(content == null || content.isEmpty()){
            System.out.println("已借阅的表中没有显示，说明没有借阅");
            return null;
        }

        String[] JsonStrings = content.split("\n");
        PairOfUidAndBookId[] pairOfUidAndBookIds = new PairOfUidAndBookId[JsonStrings.length];
        for (int i = 0; i < JsonStrings.length; i++) {
            PairOfUidAndBookId pairOfUidAndBookId = new PairOfUidAndBookId();
            String[] uiAndBookIds = JsonStrings[i].split(",");
            pairOfUidAndBookId.setBookId(Integer.parseInt(uiAndBookIds[0]));
            pairOfUidAndBookId.setBookId(Integer.parseInt(uiAndBookIds[1]));
            pairOfUidAndBookIds[i] = pairOfUidAndBookId;
        }
        return pairOfUidAndBookIds;
    }

}
